"""获取jenkins的allure报告，并发送到指定webhook"""
from pathlib import Path
import sys
project_root = Path(__file__).parent.parent
sys.path.append(str(project_root))
import jenkins
import os
import json
from utils.logger_utils import *
import requests
import urllib3
from config.Enviroments import *

# 配置Jenkins连接
server = jenkins.Jenkins(JenkinsUrl, username=UserName, password=PassWord)

# 获取最后一次构建的信息
last_build_info = server.get_info(JobName)['lastBuild']

# 本次构建的详情页URL
last_build_url = last_build_info['url']

# 拼接得到Allure报告地址
report_url = last_build_url + 'allure/'

# 完全禁用 SSL 警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def test_jenkins_connection():
    try:
        # 测试连接
        user = server.get_whoami()
        version = server.get_version()
        print(f"Jenkins连接成功! 用户: {user['fullName']}, Jenkins版本: {version}")

        # 获取所有作业列表，验证作业名称
        jobs = server.get_jobs()
        print("\n可用的作业列表:")
        for job in jobs:
            print(f"- {job['name']} (完整名称: {job.get('fullname', job['name'])})")

        return True
    except Exception as e:
        print(f"Jenkins连接失败: {e}")
        return False

def send_dingtalk_message():
    # 读取Allure测试结果数据 (示例，可根据需要调整)
    test_data = {}
    try:
        with open(AllureReportUrl, 'r') as f:
            for line in f:
                parts = line.strip().split(' ')
                if len(parts) >= 2:
                    test_data[parts[0]] = parts[1]
    except Exception as e:
        print(f"读取测试结果文件出错: {e}")

    # 提取关键测试指标
    info(f"查看测试数据：{test_data}")
    total = test_data.get('launch_retries_run', 'N/A')
    passed = test_data.get('launch_status_passed', 'N/A')
    failed = test_data.get('launch_status_failed', 'N/A')

    # 构造钉钉消息
    message = {
        "msgtype": "text",
        "text": {
            "content":
                "接口自动化测试执行完成。\n"
                f"运行总数: {total}\n"
                f"通过数量: {passed}\n"
                f"失败数量: {failed}\n"
                f"详细报告请查看: {report_url}"  # 这里加入了报告链接
        }
    }

    # 发送消息
    resp = requests.request(method='POST', url=DingTalkWebHook, json=message, headers={'Content-Type': 'application/json'},verify=False)
    print(f"钉钉消息发送状态: {resp.status_code}")

if __name__ == "__main__":
    #test_jenkins_connection()
    send_dingtalk_message()